<template>
  <Modal :visible="visible" :title="title" :closable="false" :maskClosable="false" :footer="null">
    <a-result status="warning" :title="content"> </a-result>
    <div style="text-align: center">
      <a-button type="primary" @click="handleLogout">{{ okText }}</a-button>
    </div>
  </Modal>
</template>

<script>
import { Modal } from 'ant-design-vue'

export default {
  name: 'UserInactivityDetector',
  components: {
    Modal,
  },
  props: {
    // 无操作超时时间（分钟）
    timeout: {
      type: Number,
      default: 30,
    },
    // 弹窗标题
    title: {
      type: String,
      default: '系统提示',
    },
    // 弹窗内容
    content: {
      type: String,
      default: '您长时间未执行操作，系统已自动退出。\n点击确定重新登录',
    },
    // 确认按钮文字
    okText: {
      type: String,
      default: '确定',
    },
    // 取消按钮文字
    cancelText: {
      type: String,
      default: '退出登录',
    },
    // 登出路由地址
    logoutPath: {
      type: String,
      default: '/login',
    },
  },
  data() {
    return {
      visible: false,
      timer: null,
      lastActivityTime: Date.now(),
    }
  },
  methods: {
    // 重置计时器
    resetTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.lastActivityTime = Date.now()
      this.timer = setTimeout(this.checkInactivity, this.timeout * 60 * 1000)
    },
    // 检查是否无操作
    checkInactivity() {
      const currentTime = Date.now()
      const inactiveTime = currentTime - this.lastActivityTime
      if (inactiveTime >= this.timeout * 60 * 1000) {
        this.visible = true
        // 一分钟后自动登出
        setTimeout(() => {
          if (this.visible) {
            this.handleLogout()
          }
        }, 60 * 1000)
      }
    },
    // 继续操作
    handleOk() {
      this.visible = false
      this.resetTimer()
    },
    // 登出操作
    handleLogout() {
      this.visible = false
      // 清除登录信息
      localStorage.clear()
      sessionStorage.clear()
      // 跳转到登录页
      this.$store.dispatch('Logout').then(() => {
        this.$router.push({ name: 'login' })
      })
    },
    // 用户活动事件处理
    handleUserActivity() {
      if (!this.visible) {
        this.resetTimer()
      }
    },
  },
  mounted() {
    // 监听用户活动事件
    const events = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll']
    events.forEach((event) => {
      window.addEventListener(event, this.handleUserActivity)
    })

    // 初始化计时器
    this.resetTimer()
  },
  beforeDestroy() {
    // 清理事件监听和计时器
    const events = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll']
    events.forEach((event) => {
      window.removeEventListener(event, this.handleUserActivity)
    })

    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
}
</script>
